package com.hy.aicodegeneration.langgraph4j.tools;

import cn.hutool.core.util.StrUtil;
import com.hy.aicodegeneration.langgraph4j.enums.ImageCategoryEnum;
import com.hy.aicodegeneration.langgraph4j.model.ImageCollectionResult;
import com.hy.aicodegeneration.langgraph4j.model.ImageResource;
import com.hy.aicodegeneration.manager.CosManager;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.ArrayList;

/**
 * Logo 生成工具
 * 生成简单的文字 Logo 并上传到 COS
 */
@Slf4j
@Component
public class LogoGeneratorTool {

    private final CosManager cosManager;

    public LogoGeneratorTool(CosManager cosManager) {
        this.cosManager = cosManager;
    }

    @Tool("生成 Logo 设计图片，用于网站品牌标识")
    public ImageCollectionResult generateLogos(@P("Logo 设计描述，如名称、行业、风格等") String description) {
        try {
            // 生成简单的文字 Logo
            BufferedImage logoImage = createTextLogo(description, 200, 100);
            // 转换为 Base64
            String base64Image = imageToBase64(logoImage, "png");
            // 构造 Data URL
            String dataUrl = "data:image/png;base64," + base64Image;
            // 构造图片资源对象
            ImageResource imageResource = ImageResource.builder()
                    .category(ImageCategoryEnum.LOGO)
                    .description("Generated logo for: " + description)
                    .url(dataUrl)
                    .build();
            
            List<ImageResource> imageList = new ArrayList<>();
            imageList.add(imageResource);
            return new ImageCollectionResult(imageList);
        } catch (Exception e) {
            log.error("Logo 生成失败: {}", e.getMessage(), e);
            return new ImageCollectionResult(new ArrayList<>());
        }
    }

    /**
     * 创建简单的文字 Logo
     *
     * @param text   文字内容
     * @param width  宽度
     * @param height 高度
     * @return BufferedImage 对象
     */
    private BufferedImage createTextLogo(String text, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 设置文字属性
        g2d.setColor(Color.BLACK);
        Font font = new Font("Arial", Font.BOLD, 24);
        g2d.setFont(font);

        // 计算文字位置（居中）
        FontMetrics fm = g2d.getFontMetrics();
        int x = (width - fm.stringWidth(text)) / 2;
        int y = (height - fm.getHeight()) / 2 + fm.getAscent();

        // 绘制文字
        g2d.drawString(text, x, y);
        g2d.dispose();

        return image;
    }

    /**
     * 将 BufferedImage 转换为 Base64 字符串
     *
     * @param image    BufferedImage 对象
     * @param format   图片格式（如 "png", "jpg"）
     * @return Base64 编码的字符串
     * @throws IOException IO异常
     */
    private String imageToBase64(BufferedImage image, String format) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}